﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using Newtonsoft.Json.Linq;
using ZBZH_Manage_Order.PublicMethod;
using System.IO;
using System.Configuration;

namespace ZBZH_Manage_Order.Controllers.MerchantsSettings
{
    public class FileInfoController : Controller
    {
        ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();
        private readonly string DishesPic = ConfigurationManager.AppSettings["Order_Dishes_Photos"];
        private readonly string DishesPics = ConfigurationManager.AppSettings["WeChat_Dishes_Photos"];

        /// <summary>
        /// 商品轮播图和概述、参数多张图片上传
        /// </summary>
        /// <param name="DishesID">商品ID</param>
        /// <param name="FileType">上传图片类型：1：轮播图 2：概述、参数图片</param>
        /// <returns></returns>
        public ActionResult UploadPic(string DishesID, int FileType)
        {
            try
            {
                string result = "";
                View_OperUser user = (View_OperUser)Session[SessionStorage.OperUser];
                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase file = Request.Files[0];
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(file.FileName);
                    string[] stringArray = new string[] { DishesPic, DishesPics };
                    var CarouselURL = "";
                    var ParameterOverviewURL = "";
                    var Folder = "";
                    FileInfo thefile = null;
                    if (FileType == 2)
                    {
                        Folder = "Carousel";    //商品轮播图片件夹                    
                        foreach (var item in stringArray)
                        {
                            if (!Directory.Exists(item))//判断目录是否存在
                            {
                                Directory.CreateDirectory(item);
                            }
                            thefile = new FileInfo(Path.Combine(item, Folder, DishesID, fileName));
                            CarouselURL = "/Dishes" + thefile.FullName.Replace(item, "").Replace('\\', '/');
                        }
                        Order_Carousel_T CarouselInfo = new Order_Carousel_T
                        {
                            DishesID = DishesID,
                            CarouselName = file.FileName,
                            CarouselURL = CarouselURL
                        };
                        string reg = CarouselInfo.ToJson();
                        result = service.Carousel_UploadPic(user.OperID, CarouselInfo.ToJson(), GetYZM._YZM, 1);
                        JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                        string bs = searcho["BS"].ToString();
                        string rows = searcho["rows"].ToString();
                        if (bs == "1" && rows.Count() > 0)
                        {
                            foreach (var item in stringArray)
                            {
                                thefile = new FileInfo(Path.Combine(item, Folder, DishesID, fileName));
                                Directory.CreateDirectory(thefile.DirectoryName);
                                file.SaveAs(thefile.FullName);
                            }
                            return Content(rows);
                        }
                        else
                        {
                            return Json(result);
                        }
                    }
                    else
                    {
                        Folder = "ParameterOverview";       //商品概述和参数图片件夹
                        foreach (var item in stringArray)
                        {
                            if (!Directory.Exists(item))//判断目录是否存在
                            {
                                Directory.CreateDirectory(item);
                            }
                            thefile = new FileInfo(Path.Combine(item, Folder, DishesID, fileName));
                            ParameterOverviewURL = "/Dishes" + thefile.FullName.Replace(item, "").Replace('\\', '/');
                        }
                        Order_ParameterOverview_T CarouselInfo = new Order_ParameterOverview_T
                        {
                            DishesID = DishesID,
                            ParameterOverviewName = file.FileName,
                            ParameterOverviewURL = ParameterOverviewURL
                        };
                        string reg = CarouselInfo.ToJson();
                        result = service.ParameterOverview_UploadPic(user.OperID, CarouselInfo.ToJson(), GetYZM._YZM, 1);
                        JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                        string bs = searcho["BS"].ToString();
                        string rows = searcho["rows"].ToString();
                        if (bs == "1" && rows.Count() > 0)
                        {
                            foreach (var item in stringArray)
                            {
                                thefile = new FileInfo(Path.Combine(item, Folder, DishesID, fileName));
                                Directory.CreateDirectory(thefile.DirectoryName);
                                file.SaveAs(thefile.FullName);
                            }
                            return Content(rows);
                        }
                        else
                        {
                            return Json(result);
                        }
                    }                    
                }
                return Json(new DataResult { BS = "0", Msg = "图片上传失败", total = 0, rows = null });
            }
            catch (Exception ex)
            {
                return Json(new DataResult { BS = "0", Msg = "操作异常：" + ex.Message + "请联系管理员解决", total = 0, rows = null });
            }
        }

        /// <summary>
        /// 商品单张图片删除
        /// </summary>
        /// <param name="FileInfoID"></param>
        /// <returns></returns>
        public ActionResult Photo_Delete(string FileInfoID,int FileType)
        {
            try
            {
                string result = "";
                View_OperUser user = (View_OperUser)Session[SessionStorage.OperUser];
                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }
                if (FileInfoID != null && FileType == 2)
                {
                    result = service.DishesCarousel_Photo_Del(user.OperID, FileInfoID, 1);
                }
                else
                {
                    result = service.DishesParameterOverview_Photo_Del(user.OperID, FileInfoID, 1);
                }
                
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();
                string rows = searcho["rows"].ToString();
                if (bs == "1" && rows != null)
                {
                    //删除本地保存的图片
                    string FileURL = rows;
                    string[] stringArray = new string[] { DishesPic, DishesPics };
                    foreach (var item in stringArray)
                    {
                        FileInfo file = new FileInfo((item + FileURL).Replace("/Dishes", "").Replace('\\', '/'));
                        if (file.Exists)
                        {
                            file.Delete();
                        }
                    }
                    return Content(bs);
                }
                else
                {
                    return Content(searcho["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Content("操作异常：" + ex.Message + "请联系管理员解决");
            }
        }
    }
}
